const db = wx.cloud.database()
const _ = db.command//暂时无用
import Notify from '../../../vant/notify/notify';
var util = require('../../../utils/util.js')
var app = getApp();
var daojishi;//声明一个倒计时的变量用于控制解答题的倒计时在跳转页面时停止
var x;//页数声明
var z;//收藏题目数
var tiku;//定义需要查询的数据库题库
var shoucangId//收藏的对应id
var openid
var jindu//学习进度用来上传顺序练习进度
var list=1//题目
var yeshu//底部页数
Page({

  /**
   * 页面的初始数据
   */
  data: {
    shoucangtimu: "收藏此题",
    results: "",//bmob获取的内容
    resultsshoucang:"",//收藏文件夹查询出的该题目情况
    list: 1,//题目数目
    yeshu:"",//底部的页数
    inputvalue: "",//用来清空页数input输入框的值
    answer:"",//题目答案判断后的显示内容
    inputtiankong:"",//填空题的输入内容
    disabledT:true,//填空题确认按钮是否可用控制属性
    disabledj: true,//解答题查看答案按钮是否可用控制属性
    disabledtiao: true,//跳转页数按钮是否可使用控制属性
    bgbtn: "",//填空题确认按钮颜色
    bga:"",//选择题A选项的背景色
    bgb: "",//选择题B选项的背景色
    bgc: "",//选择题C选项的背景色
    bgd: "",//选择题D选项的背景色
    bgr: "",//判断题A选项的背景色
    bgw: "",//判断题B选项的背景色
    jiedaxianshi:true,
    key: "查看答案",//查看答案按钮显示内容
    totalpagenum:"",//显示在底部的所有题目数量
    shoucangId:"",//收藏id
    touchS : [0,0],//滑动开始
    touchE : [0,0],//滑动结束
    disabledB:false//收藏和错题按钮是否可用
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that=this
    //开始就调用倒计时
    var second = 5;
    this.countDown(second)
    console.log(app.globalData.totalpagenum)
    console.log(app.globalData.openid)
    openid=app.globalData.openid
    tiku = app.globalData.shujvku//获取对应题库
    db.collection('ddata').where({
      _id:openid
    })
    .get({
      success: function(res) {
        console.log(res.data)
        if(res.data!=""){
          jindu=res.data[0][tiku]
          list=jindu
          console.log(list)
          //查询题目信息
          db.collection(tiku).where({
            list:list
          }).get().then(res => {
            console.log(res.data)
            yeshu=res.data[0].list
            that.setData({
              results:res.data,
              yeshu:res.data[0].list,
              totalpagenum:app.globalData.totalpagenum
            })
          })
          //判断题目是否已经被收藏
          db.collection('shoucang').where({
            list: list,
            bType: app.globalData.shujvku
          }).get().then(res => {
            console.log(res.data)
            if (res.data.length != 0) {
              that.setData({
                shoucangtimu: "已收藏",
                resultsshoucang: res.data,
                shoucangId:res.data[0]._id//获取id
              })
            }else{
              that.setData({
                shoucangtimu: "收藏此题",
                resultsshoucang: ""
              })
            } 
          })        
        }else{
          // db.collection('ddata').doc(openid).set({
          //   data: {
          //     dangshi2021:1,
          //     lastDate:'',
          //     lastScore:0,
          //     totalScore:0,
          //     tiku1:1,tiku2:1,tiku3:1,tiku4:1,tiku5:1,tiku6:1,tiku7:1,tiku8:1,tiku9:1,tiku10:1//预留位置
          //   }
          // }).then(res => {
          //   console.log(res)
          // }).catch(err => {
          //   console.error(err)
          // })
          console.log(list)
          //查询题目信息
          db.collection(tiku).where({
            list:1
          }).get().then(res => {
            console.log(res.data)
            yeshu=res.data[0].list
            that.setData({
              results:res.data,
              yeshu:res.data[0].list,
              totalpagenum:app.globalData.totalpagenum
            })
          })
        }

      }
    })
    
    
  },
  //倒计时函数,暂时不需要
  countDown: function (num) {
    clearInterval(daojishi)
    this.setData({
      key: num + 's后查看答案'
    });
    if (num < 1) {
      this.setData({
        disabledj: false,
        key: "点击查看答案"
      });
      return;
    }
    daojishi=setInterval(() => {
      this.countDown(num - 1)
    }, 1000);
  },
  //开始滑动屏幕
  touchStart: function(e){
    // console.log(e.touches[0].pageX)
    let sx = e.touches[0].pageX
    let sy = e.touches[0].pageY
    this.data.touchS = [sx,sy]
    this.data.touchE = [sx,sy]//touchE默认为[0,0]不在这里也赋值一下，单击屏幕也会切换题目
  },
  //滑动屏幕
  touchMove: function(e){
    let sx = e.touches[0].pageX;
    let sy = e.touches[0].pageY;
    this.data.touchE = [sx, sy]
  },
  //滑动屏幕结束切换题目
  touchEnd: function(e){
    let start = this.data.touchS
    let end = this.data.touchE
    console.log(start)
    console.log(end)
    if(start[0] < end[0] - 50){
      this.lastquestion()
      console.log('右滑',start,end)
    }else if(start[0] > end[0] + 50){
      this.nextquestion()
      console.log('左滑',start,end)
    }else{
      console.log('静止')
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    Notify({ type: 'danger', message: '滑动屏幕也可以切换题目'});//消息提示
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  //顶部操作相关函数
  //返回首页函数
  fanhuishouye: function(){
    wx.switchTab({
      url: '../index',
    })
  },
  
  //收藏和取消收藏题目相关函数
  shoucangtimu:function(){
    var that=this
    util.buttonClicked(that)//防止连击1s
    db.collection('shoucang').where({
      bType: app.globalData.shujvku//预留功能，防止后续使用多个题库
    }).count().then(res => {
      console.log(res.total)
      z = res.total
    })
    if (z > 300 && that.data.shoucangtimu == "收藏此题") {
      wx.showToast({
        title: '收藏数已超过300条上限',
        icon: "none",
        duration: 3000
      })
    }
    //先判断收藏库中是否有内容
    else if(that.data.resultsshoucang.length==0){
      db.collection('shoucang').add({
        // data 字段表示需新增的 JSON 数据
        data: {
          bType: this.data.results[0].bType,
          list: this.data.results[0].list,
          type: this.data.results[0].type,
          subject: this.data.results[0].subject,
          title: this.data.results[0].title,
          Aselect: this.data.results[0].Aselect,
          Bselect: this.data.results[0].Bselect,
          Cselect: this.data.results[0].Cselect,
          Dselect: this.data.results[0].Dselect,
          rightA: this.data.results[0].rightA,
          beizhu: this.data.results[0].beizhu
        }
      })
        .then(res => {
          console.log(res._id)
          that.setData({
            shoucangtimu:"已收藏",
            resultsshoucang:that.data.results,
            shoucangId:res._id//获取上传内容的id
          })
        })
        .catch(console.error)
      wx.showToast({
        title: '已收藏',
      })
    }else if(that.data.shoucangtimu == "已收藏"){
      shoucangId=that.data.shoucangId
      db.collection('shoucang').doc(shoucangId).remove()
      .then(console.log)
      .catch(console.error)
      wx.showToast({
        title: '已取消收藏',
      })
      that.setData({//重置data
        shoucangtimu:"收藏此题",
        resultsshoucang:""
      })
    }
  },


  //填空题相关函数
  //1.获取输入内容
  shuru: function (e) {
    var shuru = e.detail.value;
    if (shuru != "") {
      this.setData({
        inputtiankong: shuru,
        disabledT: false,
        bgbtn: "green"
      })
    } else {
      this.setData({
        disabledT: true,
        bgbtn: ""
      })
    }
  },
  //2.判断答案是否正确并显示结果
  btntiankong: function () {
    var answertiankong=this.data.results[0].rightA
    if (this.data.inputtiankong == answertiankong) {
      this.setData({
        answer:"回答正确"
      })
    } else {
      this.setData({
        answer: "回答错误，正确答案是：" + answertiankong
      })
    };
  },
  //选择题相关函数
  //选择A的函数
  selecta:function(){
    var answerxuanze=this.data.results[0].rightA
    if (answerxuanze=="A"){
      this.setData({
        bga: "green",
        bgb: "",
        bgc: "",
        bgd: "",
        answer:"回答正确!"
      })
    }else{
      this.setData({
        bga: "red",
        bgb: "",
        bgc: "",
        bgd: "",
        answer: "回答错误，正确答案是：" + answerxuanze
      })
    }
  },
  //选择B的函数
  selectb: function () {
    var answerxuanze = this.data.results[0].rightA
    if (answerxuanze == "B") {
      this.setData({
        bga: "",
        bgb: "green",
        bgc: "",
        bgd: "",
        answer: "回答正确!"
      })
    } else {
      this.setData({
        bga: "",
        bgb: "red",
        bgc: "",
        bgd: "",
        answer: "回答错误，正确答案是：" + answerxuanze
      })
    }
  },
  //选择C的函数
  selectc: function () {
    var answerxuanze = this.data.results[0].rightA
    if (answerxuanze == "C") {
      this.setData({
        bga: "",
        bgb: "",
        bgc: "green",
        bgd: "",
        answer: "回答正确!"
      })
    } else {
      this.setData({
        bga: "",
        bgb: "",
        bgc: "red",
        bgd: "",
        answer: "回答错误，正确答案是：" + answerxuanze
      })
    }
  },
  //选择D的函数
  selectd: function () {
    var answerxuanze = this.data.results[0].rightA
    if (answerxuanze == "D") {
      this.setData({
        bga: "",
        bgb: "",
        bgc: "",
        bgd: "green",
        answer: "回答正确!"
      })
    } else {
      this.setData({
        bga: "",
        bgb: "",
        bgc: "",
        bgd: "red",
        answer: "回答错误，正确答案是：" + answerxuanze
      })
    }
  },
  //多项选择题相关函数
  //选择A的函数
  Aselect:function(){
    if (this.data.bga){
      this.setData({
        bga: "",
      })
    }else{
      this.setData({
        bga: "green",
      })
    }
  },
  //选择B的函数
   Bselect:function(){
    if (this.data.bgb){
      this.setData({
        bgb: "",
      })
    }else{
      this.setData({
        bgb: "green",
      })
    }
  },
  //选择C的函数
  Cselect:function(){
    if (this.data.bgc){
      this.setData({
        bgc: "",
      })
    }else{
      this.setData({
        bgc: "green",
      })
    }
  },
  //选择D的函数
  Dselect:function(){
    if (this.data.bgd){
      this.setData({
        bgd: "",
      })
    }else{
      this.setData({
        bgd: "green",
      })
    }
  },
  //确认答案后判断正误函数
  btnduoxuan:function(){
    var answer=''
    var answerxuanze = this.data.results[0].rightA
    if(this.data.bga){
      answer='A'
    }
    if(this.data.bgb){
      answer=answer+'B'
    }
    if(this.data.bgc){
      answer=answer+'C'
    }
    if(this.data.bgd){
      answer=answer+'D'
    }
    console.log(answer)
    if(answer==answerxuanze){
      this.setData({
        answer: "回答正确!"
      })
    }else{
      this.setData({
        answer: "回答错误，正确答案是：" + answerxuanze
      })
    }
  },
  //判断题的函数
  //选择正确（A）的函数
  selectr: function () {
    var answerpanduan = this.data.results[0].rightA
    if (answerpanduan == "A") {
      this.setData({
        bgr: "green",
        bgw: "",
        answer: "回答正确!"
      })
    } else {
      this.setData({
        bgr: "red",
        bgw: "",
        answer: "回答错误，正确答案是：" + answerpanduan
      })
    }
  },
  //选择错误（B）的函数
  selectw: function () {
    var answerpanduan = this.data.results[0].rightA
    if (answerpanduan == "B") {
      this.setData({
        bgr: "",
        bgw: "green",
        answer: "回答正确"
      })
    } else {
      this.setData({
        bgr: "",
        bgw: "red",
        answer: "回答错误，正确答案是：" + answerpanduan
      })
    }
  },
  //解答题相关函数
  chakandaan:function(){
    this.setData({
      jiedaxianshi:false
    })
  },
  //底部操作区相关函数
  //上一题
  lastquestion:function(){
    console.log(list)
    if(list<2){
      this.setData({
        yeshu:1
      })
      return
    }else{
      list=list-1
    }
    this.onChange(list)
  },
  //跳页
  //1.获取输入内容
  getpagenumber: function (e) {
    var yeshu = e.detail.value;
    if (yeshu != "") {
      this.setData({
        yeshu: yeshu,
        disabledtiao: false
      })
      console.log(this.data.list)
      return;
    }
  },
  //跳转到获取的页数
  jumpquestion:function(){
    var that=this
    list=this.data.yeshu*1
    console.log(list)
    if (0 <list && list <app.globalData.totalpagenum+1){
      this.onChange(list)
    }
    else{
      wx.showToast({
        title: '请输入正确的跳转题数',
        icon: 'none',
        image: '',
        duration: 2000,
      })
    }
  },
    
  //下一题
  nextquestion: function () {
    console.log(list)
    if (list+1>app.globalData.totalpagenum) {
      this.setData({
        yeshu:app.globalData.totalpagenum
      })
      return;
    } else {
      list=list+1
    }
    this.onChange(list)
  },
  //换题后的内容
  onChange: function(list){
    var that=this
    //重置data值
    that.setData({
      shoucangtimu: "收藏此题",
      results: "",//bmob获取的内容
      resultsshoucang:"",//收藏文件夹查询出的该题目情况
      list: 1,//题目数目
      yeshu:"",//底部的页数
      inputvalue: "",//用来清空页数input输入框的值
      answer:"",//题目答案判断后的显示内容
      inputtiankong:"",//填空题的输入内容
      disabledT:true,//填空题确认按钮是否可用控制属性
      disabledj: true,//解答题查看答案按钮是否可用控制属性
      disabledtiao: true,//跳转页数按钮是否可使用控制属性
      bgbtn: "",//填空题确认按钮颜色
      bga:"",//选择题A选项的背景色
      bgb: "",//选择题B选项的背景色
      bgc: "",//选择题C选项的背景色
      bgd: "",//选择题D选项的背景色
      bgr: "",//判断题A选项的背景色
      bgw: "",//判断题B选项的背景色
      jiedaxianshi:true,
      key: "查看答案",//查看答案按钮显示内容
      totalpagenum: app.globalData.totalpagenum,//显示在底部的所有题目数量
      shoucangId:""//收藏id
    })
    //查询题目信息
    db.collection(tiku).where({
      list:list
    }).get().then(res => {
      console.log(res.data)
      yeshu=res.data[0].list
      that.setData({
        results:res.data,
        yeshu:res.data[0].list
      })
    })
    //判断题目是否已经被收藏
    db.collection('shoucang').where({
      list: list,
      bType: app.globalData.shujvku
    }).get().then(res => {
      console.log(res.data)
      if (res.data.length != 0) {
        that.setData({
          shoucangtimu: "已收藏",
          resultsshoucang: res.data,
          shoucangId:res.data[0]._id//获取id
        })
      }else{
        that.setData({
          shoucangtimu: "收藏此题",
          resultsshoucang: ""
        })
      } 
    })
    //开始就调用倒计时
    var second = 5;
    that.countDown(second)
    //储存题目进度
    if(tiku=="dangshi2021"){
      db.collection('ddata').doc(openid).update({
        data: {
          dangshi2021: list
        },
        success: function(res) {
          console.log(res)
        }
      })
    }
  },
})